package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.mapper.RegionMapper;
import com.heima.pojo.dto.RegionDto;
import com.heima.pojo.dto.RegionSearchDto;
import com.heima.pojo.entity.Region;
import com.heima.pojo.vo.RegionSearchVO;
import com.heima.pojo.vo.RegionVo;
import com.heima.service.RegionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 运营区域 服务实现类
 * </p>
 *
 * @author ljk
 * @since 2024-10-15
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {
    private final RegionMapper regionMapper;

    @Override
    public RegionSearchVO pageQuery(RegionSearchDto regionSearchDto) {
        regionSearchDto.check();
        PageHelper.startPage(regionSearchDto.getPageIndex(), regionSearchDto.getPageSize());
        List<RegionVo> list = regionMapper.pageQuery(regionSearchDto.getName());
        Page<RegionVo> p = (Page<RegionVo>) list;

        return RegionSearchVO.builder()
                .pageIndex(String.valueOf(regionSearchDto.getPageIndex()))
                .pageSize(String.valueOf(regionSearchDto.getPageSize()))
                .totalCount(String.valueOf(p.getTotal()))
                .totalPage(String.valueOf((int) Math.ceil((double) p.getTotal() / regionSearchDto.getPageSize())))
                .currentPageRecords(p.getResult())
                .build();
    }

    @Override
    public void addRegion(RegionDto regionDto) {
        Region region = new Region();
        region.setName(regionDto.getRegionName());
        region.setRemark(regionDto.getRemark());
        regionMapper.insert(region);
    }

    @Override
    public void updateRegion(String regionId, RegionDto regionDto) {
        Region region = new Region();
        region.setId(Long.valueOf(regionId));
        region.setName(regionDto.getRegionName());
        region.setRemark(regionDto.getRemark());
        regionMapper.updateById(region);
    }

    @Override
    public void delById(String regionId) {
        regionMapper.deleteById(regionId);
    }
}
